package top.ooyyh.controller;

import top.ooyyh.dao.TaskDao;
import top.ooyyh.model.Task;
import top.ooyyh.model.User;
import top.ooyyh.model.TaskStatistics;
import top.ooyyh.util.TerminalUI;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * 主界面控制器
 */
public class MainController {
    private Scanner scanner = new Scanner(System.in);
    private User currentUser;
    private TaskDao taskDao = new TaskDao();

    public MainController(User user) {
        this.currentUser = user;
    }

    /**
     * 显示主菜单
     */
    public void showMainMenu() {
        while (true) {
            TerminalUI.clearScreen();
            TerminalUI.printTitle("任务管理系统");
            TerminalUI.printUserCard(currentUser.getUsername(), currentUser.getRole());
            List<String> menuItems = new ArrayList<>();
            menuItems.add("查看任务列表");
            menuItems.add("创建新任务");
            menuItems.add("编辑任务");
            menuItems.add("删除任务");
            menuItems.add("任务统计");
            menuItems.add("退出系统");
            TerminalUI.printMenu("请选择操作", menuItems);
            System.out.print(TerminalUI.CYAN + "➜ " + TerminalUI.RESET + "请输入选项 (1-6): ");
            String choice = scanner.nextLine().trim();
            switch (choice) {
                case "1":
                    showTaskList();
                    break;
                case "2":
                    createTask();
                    break;
                case "3":
                    editTask();
                    break;
                case "4":
                    showDeleteTask();
                    break;
                case "5":
                    showTaskStatistics();
                    break;
                case "6":
                    return;
                default:
                    TerminalUI.printError("无效选项，请重试。");
                    TerminalUI.waitForEnter();
            }
        }
    }

    private int safeLongToInt(Long value) {
        if (value == null) return 0;
        if (value > Integer.MAX_VALUE) return Integer.MAX_VALUE;
        if (value < Integer.MIN_VALUE) return Integer.MIN_VALUE;
        return value.intValue();
    }

    private void createTask() {
        TerminalUI.clearScreen();
        TerminalUI.printTitle("创建新任务");
        String title;
        while (true) {
            System.out.print(TerminalUI.CYAN + "标题" + TerminalUI.RESET + " (必填): ");
            title = scanner.nextLine().trim();
            if (!title.isEmpty()) break;
            TerminalUI.printError("标题不能为空。");
        }
        System.out.print(TerminalUI.CYAN + "描述" + TerminalUI.RESET + " (可选): ");
        String description = scanner.nextLine().trim();
        if (description.isEmpty()) description = null;
        System.out.print(TerminalUI.CYAN + "截止日期" + TerminalUI.RESET + " (格式 yyyy-MM-dd，可选): ");
        String dueDate = scanner.nextLine().trim();
        if (dueDate.isEmpty()) dueDate = null;
        System.out.print(TerminalUI.CYAN + "优先级" + TerminalUI.RESET + " (LOW|MEDIUM|HIGH，默认MEDIUM): ");
        String priority = scanner.nextLine().trim();
        if (priority.isEmpty()) priority = "MEDIUM";
        Task task = new Task(title, description, dueDate, safeLongToInt(currentUser.getId()), currentUser.getUsername());
        task.setPriority(priority);
        boolean success = taskDao.insertTask(task);
        if (success) {
            TerminalUI.printSuccess("任务已创建: ID=" + task.getId());
        } else {
            TerminalUI.printError("任务创建失败。");
        }
        TerminalUI.waitForEnter();
    }

    private void editTask() {
        List<Task> tasks = taskDao.getTasksByUserId(safeLongToInt(currentUser.getId()));
        if (tasks.isEmpty()) {
            TerminalUI.printInfo("当前没有任务。");
            TerminalUI.waitForEnter();
            return;
        }
        showTaskListBrief(tasks);
        System.out.print(TerminalUI.CYAN + "➜ " + TerminalUI.RESET + "输入要编辑的任务 ID (或输入 0 返回): ");
        String raw = scanner.nextLine().trim();
        int id;
        try {
            id = Integer.parseInt(raw);
        } catch (NumberFormatException e) {
            TerminalUI.printError("无效的数字。");
            TerminalUI.waitForEnter();
            return;
        }
        if (id == 0) return;
        Task target = taskDao.getTaskById(id, safeLongToInt(currentUser.getId()));
        if (target == null) {
            TerminalUI.printError("未找到 ID 为 " + id + " 的任务。");
            TerminalUI.waitForEnter();
            return;
        }
        TerminalUI.clearScreen();
        TerminalUI.printTitle("编辑任务 #" + id);
        TerminalUI.printInfo("当前内容：");
        System.out.println(target.toString());
        System.out.println();
        System.out.print(TerminalUI.CYAN + "新标题" + TerminalUI.RESET + " (回车保留原值): ");
        String title = scanner.nextLine().trim();
        if (!title.isEmpty()) target.setTitle(title);
        System.out.print(TerminalUI.CYAN + "新描述" + TerminalUI.RESET + " (回车保留原值): ");
        String desc = scanner.nextLine().trim();
        if (!desc.isEmpty()) target.setDescription(desc);
        System.out.print(TerminalUI.CYAN + "新截止日期" + TerminalUI.RESET + " (yyyy-MM-dd, 回车保留原值): ");
        String due = scanner.nextLine().trim();
        if (!due.isEmpty()) target.setDueDate(due);
        System.out.print(TerminalUI.CYAN + "新状态" + TerminalUI.RESET + " (TODO|IN_PROGRESS|DONE, 回车保留原值): ");
        String status = scanner.nextLine().trim();
        if (!status.isEmpty()) target.setStatus(status);
        System.out.print(TerminalUI.CYAN + "新优先级" + TerminalUI.RESET + " (LOW|MEDIUM|HIGH, 回车保留原值): ");
        String priority = scanner.nextLine().trim();
        if (!priority.isEmpty()) target.setPriority(priority);
        boolean success = taskDao.updateTask(target);
        if (success) {
            TerminalUI.printSuccess("任务已更新。");
        } else {
            TerminalUI.printError("任务更新失败。");
        }
        TerminalUI.waitForEnter();
    }

    private void showTaskList() {
        List<Task> tasks = taskDao.getTasksByUserId(safeLongToInt(currentUser.getId()));
        TerminalUI.clearScreen();
        TerminalUI.printTitle("我的任务列表");
        if (tasks.isEmpty()) {
            TerminalUI.printInfo("暂无任务。");
        } else {
            for (Task t : tasks) {
                System.out.println(t.toString());
                System.out.println("--------------------------------------------------");
            }
        }
        TerminalUI.waitForEnter();
    }

    private void showTaskListBrief(List<Task> tasks) {
        TerminalUI.clearScreen();
        TerminalUI.printTitle("任务列表（简要）");
        if (tasks.isEmpty()) {
            TerminalUI.printInfo("暂无任务。");
        } else {
            for (Task t : tasks) {
                System.out.printf("ID:%d  标题:%s  截止:%s  状态:%s  优先级:%s\n",
                        t.getId(), t.getTitle(), t.getDueDate() == null ? "-" : t.getDueDate(), t.getStatus(), t.getPriority());
            }
        }
        System.out.println();
    }

    /**
     * 显示删除任务界面
     */
    private void showDeleteTask() {
        List<Task> tasks = taskDao.getTasksByUserId(safeLongToInt(currentUser.getId()));
        if (tasks.isEmpty()) {
            TerminalUI.clearScreen();
            TerminalUI.printTitle("删除任务");
            TerminalUI.printInfo("当前没有任务可删除。");
            TerminalUI.waitForEnter();
            return;
        }
        showTaskListBrief(tasks);
        System.out.print(TerminalUI.CYAN + "➜ " + TerminalUI.RESET + "输入要删除的任务 ID (或输入 0 返回): ");
        String raw = scanner.nextLine().trim();
        int id;
        try {
            id = Integer.parseInt(raw);
        } catch (NumberFormatException e) {
            TerminalUI.printError("无效的数字。");
            TerminalUI.waitForEnter();
            return;
        }
        if (id == 0) return;
        Task target = taskDao.getTaskById(id, safeLongToInt(currentUser.getId()));
        if (target == null) {
            TerminalUI.printError("未找到 ID 为 " + id + " 的任务。");
            TerminalUI.waitForEnter();
            return;
        }
        System.out.print(TerminalUI.CYAN + "确认删除任务 '" + target.getTitle() + "' ? (y/N): " + TerminalUI.RESET);
        String confirm = scanner.nextLine().trim().toLowerCase();
        if (!confirm.equals("y") && !confirm.equals("yes")) {
            TerminalUI.printInfo("已取消删除。");
            TerminalUI.waitForEnter();
            return;
        }
        boolean ok = taskDao.deleteTask(id, safeLongToInt(currentUser.getId()));
        if (ok) {
            TerminalUI.printSuccess("任务已删除。");
        } else {
            TerminalUI.printError("任务删除失败，可能任务已不存在或没有权限。");
        }
        TerminalUI.waitForEnter();
    }

    /**
     * 显示任务统计
     */
    private void showTaskStatistics() {
        int uid = safeLongToInt(currentUser.getId());
        TaskStatistics stats = taskDao.getStatisticsByUserId(uid);
        TerminalUI.clearScreen();
        TerminalUI.printTitle("任务统计");
        if (stats == null) {
            TerminalUI.printInfo("无法获取统计数据。");
            TerminalUI.waitForEnter();
            return;
        }
        System.out.println("总任务数: " + stats.getTotal());
        System.out.println("按状态:");
        System.out.println("  TODO: " + stats.getTodo());
        System.out.println("  IN_PROGRESS: " + stats.getInProgress());
        System.out.println("  DONE: " + stats.getDone());
        System.out.println("按优先级:");
        System.out.println("  LOW: " + stats.getLow());
        System.out.println("  MEDIUM: " + stats.getMedium());
        System.out.println("  HIGH: " + stats.getHigh());
        TerminalUI.waitForEnter();
    }
}
